package com.minelx.statementsplus.cha.webauto;

import com.minelx.landisk.filesystem.core.File;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.FileHeader;

import java.util.List;

import static com.minelx.landisk.filesystem.core.PathFactory.file;

public class ResultFile {
	private final File file;

	public ResultFile(File file) {
		if (!file.exists()) {
			throw new IllegalArgumentException("file doesn't exists.");
		}
		this.file = file;
	}

	public File extractCsv() {
		ZipFile zipFile = new ZipFile(file.getAbsolutePath());
		try {
			List<FileHeader> all = zipFile.getFileHeaders();
			FileHeader fileExtracted = all.get(0);
			File result = file.sibling(fileExtracted.getFileName()).as(file());
			result.deleteIfExists();
			zipFile.extractFile(fileExtracted, file.container().getAbsolutePath());
			return result;
		} catch (ZipException e) {
			throw new RuntimeException("file extraction failed: " + file, e);
		}
	}
}
